package com.cxyw.qqrobot;

import com.cxyw.qqrobot.service.QQRobotService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

//前端连接的地址路径
@ServerEndpoint(value = "/")
@Component
@Slf4j
public class QQWebSocket {




    private static QQRobotService qqRobotService;

    @Autowired
    public void setQqRobotService(QQRobotService qqRobotService) {
        QQWebSocket.qqRobotService = qqRobotService;
    }


    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    private static CopyOnWriteArraySet<QQWebSocket> webSockets =new CopyOnWriteArraySet<>();
    //用来存放每个客户端对应的WebSocket对象。若要实现服务端与单一客户端通信的话，可以使用Map来存放，其中Key可以为用户标识
    private static Map<String,Session> sessionPool = new HashMap<String,Session>();

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSockets.add(this);
        System.out.println("【websocket消息】有新的连接，总数为:"+webSockets.size());
        sendAllMessage("欢迎您，客户端");
    }

    @OnClose
    public void onClose() {
        webSockets.remove(this);
        System.out.println("【websocket消息】连接断开，总数为:"+webSockets.size());
    }

    @OnMessage
    public void onMessage(String message) {
        QQWebSocket.qqRobotService.handleQQMessage(message);
    }

    // 此为广播消息
    public void sendAllMessage(String message) {
        for(QQWebSocket webSocket : webSockets) {
            System.out.println("【websocket消息】广播消息:"+message);
            try {
                webSocket.session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    // 此为单点消息 (发送文本)
    public void sendTextMessage(String key, String message) {
        Session session = sessionPool.get(key);
        if (session != null) {
            try {
                session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}


